<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("表单分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" content="分类管理" placement="top">
              <el-button @click="handleSettingClick" type="text" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          node-key="id"
          :highlight-current="true"
          :data="dataItemTree_FormSort"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="el-icon-notebook-2"></i>
            {{ node.label }}
          </span>
        </el-tree>
      </l-panel>
    </template>

    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input placeholder="请输入模版名称" @keyup.enter.native="hanleSearch" v-model="keyWord" size="mini">
            <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_CreateDate="scope">
          {{ lr_dateFormat(scope.row.f_CreateDate) }}
        </template>
        <template v-slot:f_Category="scope">
          {{ lr_dataItemName(lr_dataItem["FormSort"], scope.row.f_Category) }}
        </template>
        <template v-slot:f_FormType="scope">
          <el-tag v-if="scope.row.f_FormType == 1" size="mini" type="warning">视图表单</el-tag>
          <el-tag v-if="scope.row.f_FormType == 0" size="mini" type="success">常规表单</el-tag>
          <el-tag v-if="scope.row.f_FormType == 2" size="mini" type="success">接口模式</el-tag>
        </template>
        <template v-slot:f_EnabledMark="scope">
          <el-tag v-if="scope.row.f_Type != 1" size="mini">草稿</el-tag>
          <el-switch
            v-else
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>
    <l-fullscreen-dialog
      :title="$t(`表单设计`)"
      :headerMidWidth="480"
      :visible.sync="formVisible"
      :isStep="true"
      :steps="stepArr"
      :stepActive.sync="stepActive"
      :validateSteps="handleValidateSteps"
      @ok="handleSave"
      @closed="handleClosed"
      @opened="handleOpened"
      ref="formDialog"
    >
      <template #headerRight>
        <el-button @click="handleSaveDraft()" type="warning" size="mini">暂存</el-button>
      </template>
      <formDesign-form ref="form" :stepActive="stepActive" @setFormType="setFormType"> </formDesign-form>
    </l-fullscreen-dialog>

    <l-drawer :title="$t('分类管理')" :visible.sync="classifysVisible" :showOk="false" :showClose="false" size="800px">
      <l-dataitem-index classifyCode="FormSort"></l-dataitem-index>
    </l-drawer>

    <l-dialog
      :title="`${$t('表单预览')}-${$t(previewTitle)}`"
      :visible.sync="previewVisible"
      :height="600"
      width="800px"
      :hasBtns="false"
      @opened="handlePreviewOpened"
      @closed="handlePreviewClosed"
    >
      <preview ref="preview"></preview>
    </l-dialog>

    <l-drawer
      :title="`${$t('历史记录')}-${$t(historyTitle)}`"
      :visible.sync="historyVisible"
      :showOk="false"
      :showClose="false"
      size="640px"
      @opened="HistoryOpened"
    >
      <history
        ref="HistoryForm"
        :schemeInfoId="schemeInfoId"
        :schemeId="schemeId"
        :updateSchemeId="updateSchemeId"
      ></history>
    </l-drawer>
  </l-layout>
</template>

<script>
const api = window.$api.custmerForm.scheme;

import formDesignForm from "./form";
import preview from "./preview";
import history from "./history";
export default {
  components: {
    formDesignForm,
    preview,
    history,
  },
  data() {
    return {
      lr_isPage: true,
      // 设计表单
      stepActive: 0,
      stepPrevBtn: true,
      stepNextBtn: false,
      stepSaveBtn: true,
      formVisible: false,

      // 左侧树形
      treeLoading: false,
      treeCategory: "",
      classifysVisible: false,

      // 表格
      columns: [
        { label: "名称", prop: "f_Name", minWidth: "150" },
        { label: "分类", prop: "f_Category", width: "120", align: "center" },
        { label: "类型", prop: "f_FormType", width: "100", align: "center" },

        { label: "状态", prop: "f_EnabledMark", width: "64", align: "center" },
        { label: "创建人", prop: "f_CreateUserName", width: "100", align: "center" },
        { label: "创建时间", prop: "f_CreateDate", width: "160" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "Delete", label: "删除" },
        { prop: "Preview", label: "预览" },
        { prop: "History", label: "历史记录" },
      ],
      tableLoading: false,

      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableData: [],
      keyWord: "",

      formEdit: false,
      formEditRow: null,
      formLoading: false,
      formLoadingText: "",

      // 表单预览
      previewVisible: false,
      previewTitle: "",
      previewLoading: false,

      //
      historyVisible: false,
      historyTitle: "",
      schemeInfoId: "",
      schemeId: "",

      stepArr: ["基本配置", "表单设计"],
      FormType: 0,
    };
  },
  created() {
    this.lr_loadDataItem("FormSort");
    this.loadTablePageData();
  },
  mounted() {},
  computed: {
    dataItemTree_FormSort() {
      return this.lr_dataItemTree(this.lr_dataItem["FormSort"]);
    },
  },
  methods: {
    //表单步骤
    setFormType(e) {
      this.FormType = e;
      //console.log("前端测试getNum" + e);
      this.stepArr = e == 2 ? ["基本配置", "表单设计", "接口输出"] : ["基本配置", "表单设计"];
    },

    loadTablePageData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC",
        category: this.treeCategory,
        keyword: this.keyWord,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows;
          this.tableTotal = data.records;

          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    hanleSearch() {
      this.loadTablePageData();
    },

    handleSettingClick() {
      this.classifysVisible = true;
    },
    handleNodeClick(node) {
      this.treeCategory = node.value;
      this.loadTablePageData(true);
    },

    // 表单部分
    handleAdd() {
      this.formEdit = false;
      this.showForm();
    },
    handleEdit($index, row) {
      // console.log("点击按钮：");
      // console.log(row);
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm();
    },
    handleDelete($index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.tableData.splice($index, 1);
            this.tableTotal--;
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSaveDraft() {
      this.handleSave(this.$refs.formDialog.showLoading, this.$refs.formDialog.hideLoading, true);
    },
    handleSave(showLoading, hideLoading, isDraft) {
      showLoading("保存数据中...");
      if (!isDraft && !this.$refs.form.validateForm()) {
        hideLoading();
        return;
      }

      let postData = this.$refs.form.getForm(isDraft);
      //console.log("F_Scheme",JSON.parse(postData.scheme.F_Scheme))
      if (this.formEdit) {
        api
          .update(this.formEditRow.f_Id, postData)
          .then(() => {
            this.loadTablePageData(true);
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            if (!isDraft) {
              this.formVisible = false;
            }
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        api
          .add(postData)
          .then((res) => {
            this.formEditRow = res.data.data;
            this.formEdit = true;
            this.loadTablePageData(true);
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            if (!isDraft) {
              this.formVisible = false;
            }
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      }
    },
    handleEnableChange(row) {
      api.updateState(row.f_Id, row.f_EnabledMark).then(() => {
        this.$message({
          type: "success",
          message: "更新成功!",
        });
      });
    },
    handlePreview($index, row) {
      this.formEditRow = row;
      this.previewLoading = true;
      this.previewVisible = true;
      this.previewTitle = row.f_Name;
    },
    async handlePreviewOpened(showLoading, hideLoading) {
      showLoading("加载中...");
      const data = await this.$awaitWraper(api.getHistory(this.formEditRow.f_SchemeId));
      data && this.$refs.preview.setForm(data);
      hideLoading();
    },
    handlePreviewClosed() {
      this.$refs.preview.resetForm();
    },

    handleHistory($index, row) {
      this.formEditRow = row;
      this.historyTitle = row.f_Name;
      this.schemeId = row.f_SchemeId;
      this.schemeInfoId = row.f_Id;

      this.historyVisible = true;
    },
    HistoryOpened() {
      this.$refs.HistoryForm.loadTablePageData();
    },
    updateSchemeId(id) {
      this.schemeId = id;
      this.formEditRow.f_SchemeId = id;
    },
    showForm() {
      this.formVisible = true;
    },

    handleValidateSteps() {
      return this.$refs.form.validateSteps();
    },
    async handleOpened(showLoading, hideLoading) {
      //console.log("当前测试：打开弹窗");
      if (this.formEdit) {
        showLoading("加载数据中...");
        var res = await this.$refs.form.setForm(this.formEditRow.f_Id);
        hideLoading();
        if (!res) {
          this.formVisible = false;
        }
      }
    },
    handleClosed() {
      this.$refs.form.resetForm();
    },
  },
};
</script>
